import { useState, useEffect } from 'react';

// 定义设置类型
interface AppSettings {
  darkMode: boolean;
  language: string;
  notificationEnabled: boolean;
  soundEnabled: boolean;
  autoDownload: 'wifi' | 'cellular' | 'never';
  locationEnabled: boolean;
  mapType: 'standard' | 'satellite' | 'terrain';
  syncSettings: boolean;
  analyticsEnabled: boolean;
}

// 存储键
const STORAGE_KEY = 'multilingual_travel_assistant_settings';

// 默认设置
const DEFAULT_SETTINGS: AppSettings = {
  darkMode: false,
  language: 'zh',
  notificationEnabled: true,
  soundEnabled: true,
  autoDownload: 'wifi',
  locationEnabled: true,
  mapType: 'standard',
  syncSettings: true,
  analyticsEnabled: true
};

// 获取存储的设置
const getStoredSettings = (): AppSettings => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : DEFAULT_SETTINGS;
  } catch (error) {
    console.error('Failed to load settings from storage:', error);
    return DEFAULT_SETTINGS;
  }
};

// 保存设置到存储
const saveSettingsToStorage = (settings: AppSettings): void => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
  } catch (error) {
    console.error('Failed to save settings to storage:', error);
  }
};

// 监听系统主题变化
const useSystemTheme = () => {
  const [systemDarkMode, setSystemDarkMode] = useState(false);

  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    setSystemDarkMode(mediaQuery.matches);

    const handleChange = (e: MediaQueryListEvent) => {
      setSystemDarkMode(e.matches);
    };

    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, []);

  return systemDarkMode;
};

// 设置服务
const useSettingsService = () => {
  const [settings, setSettings] = useState<AppSettings>(DEFAULT_SETTINGS);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const systemDarkMode = useSystemTheme();

  // 加载设置
  useEffect(() => {
    try {
      setSettings(getStoredSettings());
      setIsLoading(false);
    } catch (err) {
      setError('Failed to load settings');
      setIsLoading(false);
    }
  }, []);

  // 更新设置
  const updateSettings = (newSettings: Partial<AppSettings>) => {
    const updatedSettings = {
      ...settings,
      ...newSettings
    };

    setSettings(updatedSettings);
    saveSettingsToStorage(updatedSettings);
  };

  // 获取当前主题模式（考虑系统设置和用户设置）
  const getCurrentTheme = () => {
    // 如果用户明确设置了主题，则使用用户设置
    if (settings.darkMode !== undefined) {
      return settings.darkMode ? 'dark' : 'light';
    }
    // 否则使用系统设置
    return systemDarkMode ? 'dark' : 'light';
  };

  return {
    settings,
    isLoading,
    error,
    updateSettings,
    getCurrentTheme,
    systemDarkMode
  };
};

export default useSettingsService;